package com.liyuncong.algorithm.algorithm_similarity.impl;

import java.util.BitSet;

import com.liyuncong.algorithm.algorithm_similarity.entity.Vector;
import com.liyuncong.algorithm.algorithm_similarity.similarity.ComputeSimilarity;
import com.liyuncong.algorithm.algorithm_similarity.util.VectorUtil;
/**
 * 杰卡德距离：衡量两个集合之间的距离；
 * 集合用向量表示，包含某个元素，向量的相应分量设置为1，否则为0
 * @author yuncong
 *
 */
public class JaccardSimilarityCoefficient implements ComputeSimilarity {

	public float compute(Vector vector1, Vector vector2) {
		BitSet bitSet1 = vector1.getBitSet();
		BitSet bitSet1Copy = VectorUtil.copyBitSet(bitSet1);
		BitSet bitSet2 = vector2.getBitSet();
		bitSet1Copy.or(bitSet2);
		// or表示两个个集合中出现过的所有元素的个数
		int or = VectorUtil.getNumofNonzero(bitSet1Copy);
		// or等于0，表示两个集合都是空集
		if (or == 0) {
			return 0;
		}
		
		bitSet1.and(bitSet2);
		// and表示集合中共有元素个数，也是是向量中同时为非0元素的个数
		int and = VectorUtil.getNumofNonzero(bitSet1);
		
		return (float) and / or;
	}

}
